<?php
@header('Content-Type: text/html; charset=utf-8');
include_once('sender.php');
include_once('render.php');

function query_all_user_info($mysql, $allu_select_sql, $ussi_select_sql)
{
  $user_info_array = array();

  $result = $mysql->query($allu_select_sql);
  while ($row = $result->fetch_object())
  {
    if ($row->status == "active")
    {
      $user_info = new UserInfo($row, $mysql, $ussi_select_sql);
      $user_info_array[$user_info->uid] = $user_info;
    }
  }

  //print_r($user_info_array);
  return $user_info_array;
}

function query_all_user_ss_data($user_info_array, $ussd_select_stmt, $ussi_update_stmt)
{
  foreach ($user_info_array as $user_info)
  {
    $user_data = new UserData($user_info, $ussd_select_stmt);
    dispatch_user_data($user_data, $ussi_update_stmt);
  }
}

function dispatch_user_data($user_data, $ussi_update_stmt)
{
  $nick = $user_data->user_info->nick;
  $mail_title = "Dear $nick 你的订阅消息 ".date("Ymd [A]");
  $mail_body = render_ss_data($user_data);
  //print_r($mail_title);
  //print_r($mail_body);
  if (send_mail($user_data->user_info->email, $mail_title, $mail_body))
  {
    foreach ($user_data->user_info->ussi_array as $ussi)
    {
      $ussi_update_stmt->bind_param("iiss", $ussi->last_timestamp, $user_data->user_info->uid, $ussi->source, $ussi->board);
      $ussi_update_stmt->execute();
    }
  }
}

function dispatcher()
{
  global $allu_select_sql;
  global $ussi_select_sql;
  global $ussd_select_ps;
  global $ussi_update_ps;

  $mysql = new mysqli("localhost", "ss", "ss", "db_subscribe");
  $mysql->set_charset("utf8");
  $ussd_select_stmt = $mysql->prepare($ussd_select_ps);
  $ussi_update_stmt = $mysql->prepare($ussi_update_ps);
  
  $user_info_array = query_all_user_info($mysql, $allu_select_sql, $ussi_select_sql);
  query_all_user_ss_data($user_info_array, $ussd_select_stmt, $ussi_update_stmt);

  $mysql->close();
}

$user_select_sql = "select uid,nick,email,phone,status from ss_user_info where email=";
$allu_select_sql = "select uid,nick,email,phone,status from ss_user_info;";
$ussi_select_sql = "select source,board,last_timestamp,keywords,reply_limit from ss_user_keyword where uid=";
#$ussd_select_ps = "
#    select url,board,title,reply,timestamp 
#    from ss_smth_article 
#    where url in (
#      select url 
#      from ss_smth_rindex 
#      where 
#        keyword=? 
#        and board=? 
#        and timestamp>?
#      group by url)
#    and reply>=?
#    order by board,timestamp;";
$ussd_select_ps = "
    select t1.url,t1.board,t1.title,t1.reply,t1.timestamp
    from ss_smth_article as t1, ss_smth_rindex as t2
    where
      t1.url=t2.url
      and t2.keyword in (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
      and t2.board=?
      and t2.timestamp>?
      and t1.reply>=?
    group by t1.url
    order by t1.timestamp";
$ussi_update_ps = "update ss_user_keyword set last_timestamp=? where uid=? and source=? and board=?;";

//dispatcher();
?>
